package com.example.search.controller;

import com.example.common.util.R;
import com.example.common.util.ResultCodeRecord;
import com.example.model.user.pojo.User;
import com.example.search.dto.HistorySearchDto;
import com.example.search.pojo.UserSearch;
import com.example.utils.thread.UserThreadLocal;
import com.mongodb.client.result.DeleteResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/v1/")
@Tag(name = "搜索历史管理")
@Slf4j
public class UserSearchController {
    @Autowired
    private MongoTemplate mongoTemplate;

    @GetMapping(value = "/get")
    @Operation(summary = "获取搜索历史")
    public R getAll() {
        List< UserSearch > userSearches = mongoTemplate.findAll(UserSearch.class);
        return R.ok("获取搜索历史成功").data("userSearches", userSearches);
    }

    @PostMapping(value = "/history/load")
    @Operation(summary = "搜索历史记录")
    public R findUserSearch() {
        // 获取当前用户
        User user = UserThreadLocal.getUser();
        if (user == null) {
            return R.error(ResultCodeRecord.NEED_ADMIND);
        }
        // 根据用户查询数据，按照时间倒序
        Query query = Query.query(Criteria.where("userId").is(user.getUserId()));
        query.with(Sort.by(Sort.Direction.DESC, "createTime"));
        List< UserSearch > userSearches = mongoTemplate.find(query, UserSearch.class);
        if (!userSearches.isEmpty()) {
            R.ok("搜索历史成功").data("userSearches", userSearches);
        } else if (userSearches == null) {
            return R.error("搜索历史没找到数据");
        } else {
            return R.error("搜索历史失败");
        }
        return R.error("搜索历史失败，请你稍后重试");
    }

    @DeleteMapping(value = "/history/deleteHistory/{id}")
    @Operation(summary = "删除历史记录")
    public R deleteUserSearch(@PathVariable("id") String id) {
        HistorySearchDto historySearchDto = new HistorySearchDto();
        historySearchDto.setId(id);
        // 1、检查参数
        if (historySearchDto.getId() == null) {
            return R.error(ResultCodeRecord.PARAM_INVALID);
        }
        // 2、判断是否登录
        User user = UserThreadLocal.getUser();
        if (user == null) {
            return R.error(ResultCodeRecord.NEED_ADMIND);
        }
        Query query = Query.query(Criteria.where("id").is(historySearchDto.getId()));
        DeleteResult remove = mongoTemplate.remove(query, UserSearch.class);
        log.info("Deleting from UserSearch where id: {}", historySearchDto.getId());
        log.info("Delete result: {}", remove);
        if (remove.getDeletedCount() > 0) {
            return R.ok("删除历史记录成功");
        } else {
            return R.error("删除历史记录失败");

        }
    }
}
